#include "SwitchLElement.h"
#include <QWidget>
#include <QObject>
#include <QTimer>
SwitchLElement::SwitchLElement(const QString& iPath, const int& index, const QString& name, const QString& cmdKey)
	:LeafElement(iPath, index, cmdKey), _name(name), _cmdKey(cmdKey), _textWidth(200), _drawLength(name.length()),
	_timer(nullptr), _isDrawFlag(false),_timerInterval(500)
{

}

void SwitchLElement::drawElement(QWidget* widget, QPainter* painter, bool bSelected, const QRect& rect)
{
	initTimer(widget);
	_isDrawFlag = true;
	this->setRect(rect);
	LeafElement::drawElement(widget, painter, bSelected,rect);
	drawName(painter);
	drawStatus(painter);
	_isDrawFlag = false;

}

void SwitchLElement::drawStatus(QPainter* painter)
{
	QPixmap pixmap(getCommandKeyIndex(_cmdKey) == 1 ? ":/UI/icon/common/on.png" : ":/UI/icon/common/off.png");
	if (pixmap.isNull())
		return;
	QRect pixRect(_rect.topLeft() + QPoint(8 + _textWidth, 0), QSize(58, 30));
	painter->drawPixmap(pixRect, pixmap);

}

void SwitchLElement::drawName(QPainter* painter)
{
	if (_drawLength > 0) {
		QFont font;
		font.setPixelSize(30);
		font.setFamily("Source Han Sans K");
		painter->setFont(font);
		QPen pen(QColor(255, 255, 255));
		painter->setPen(pen);
		QFontMetrics metrics(font);
		QString text(getTranslate(_name));

		int w = metrics.width(text);
		QRect textRect(_rect.topLeft() + QPoint(8, 0), QSize(_textWidth, metrics.height()));
		if (w > textRect.width() && _timer != nullptr) {
			if (!_timer->isActive()) {
				_timer->start(_timerInterval);
			}
		}
		painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text.right(_drawLength));
	}
}

void SwitchLElement::initTimer(QWidget* widget)
{
	if (widget != nullptr && _timer == nullptr) {
		_timer = new QTimer(widget);
		QObject::connect(_timer, &QTimer::timeout, [&]() {
			this->slotTimer();
			});
	}
}

void SwitchLElement::slotTimer()
{
	if (_isDrawFlag)
	{
		return;
	}
	QWidget* widget = qobject_cast<QWidget*>(_timer->parent());
	_drawLength--;
	if (_drawLength <= 0) {
		_drawLength = _name.length();
	}
	widget->update(_rect);
}

SwitchLElement::~SwitchLElement()
{

	if (_timer != nullptr) {
		delete _timer;
		_timer = nullptr;
	}

}
